﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace VisionApplication
{
    public static class Serializer
    {
        /// <summary>
        /// Function to save object to external file
        /// </summary>
        /// <param name="_Object">object to save</param>
        /// <param name="_FileName">File name to save object</param>
        /// <returns>Return true if object save successfully, if not return false</returns>
        public static bool ObjectToFile( this object _Object, string _FileName)
        {
            try
            {
                Stream streamWrite = File.Create(_FileName);
                BinaryFormatter binaryWrite = new BinaryFormatter();
                binaryWrite.Serialize(streamWrite, _Object);
                
                streamWrite.Close();

                return true;
            }
            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
            }

            // Error occured, return null
            return false;
        }

        public static object FileToObject(this object _Object, string _FileName)
        {
            try
            {
                Stream streamRead = File.OpenRead(_FileName);
                BinaryFormatter binaryRead = new BinaryFormatter();
                _Object = (object)binaryRead.Deserialize(streamRead);
                streamRead.Close();

                return _Object;
            }
            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
            }

            // Error occured, return null
            return false;
        }
    }
}



